package gw.com.android.ui.quote2.addquote;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import gw.com.android.app.AppContances;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.utils.MobclickEventUtlis;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.app.PushMsgTabFragment;
import www.com.library.model.DataItemDetail;
import www.com.library.util.CommonUtils;
import www.com.library.view.EfficientRecyclerView;
import www.com.library.view.RecycleViewDivider;

/**
 * 行情报价界面
 */
public class QuoteAddFragment extends PushMsgTabFragment {

    /**
     * 产品列表控件
     **/
    @BindView(R.id.lv_product_list)
    EfficientRecyclerView mListView;
    @BindView(R.id.percent_view)
    TextView mPrecentView;
    @BindView(R.id.empty_title)
    View mEmptyLayout;
    private QuoteAddSelfAdapter mAdapter;

    private String mZoneType = GTSConst.ZONE_TYPE_SELF + "";
    private int mSortType = AppContances.SORT_NORMAL_TYPE;

    public QuoteAddFragment() {
    }

    public static QuoteAddFragment newInstance(String mZoneType) {
        QuoteAddFragment fragment = new QuoteAddFragment();
        Bundle args = new Bundle();
        args.putString("mZoneType", mZoneType);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mZoneType = getArguments().getString("mZoneType");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return mRootView;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_new_quote_add;
    }

    @Override
    protected void initLayoutView() {
        ButterKnife.bind(this, mRootView);
        // 线性布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        // 设置布局管理器
        mListView.setLayoutManager(linearLayoutManager);
//        mListView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL, R.drawable.common_divider_left20_bg));//不要使用RecyclerView自带的分割线，很难用
    }

    @Override
    protected void initViewData() {
        mAdapter = new QuoteAddSelfAdapter(this, mZoneType, getActivity());
        mListView.setAdapter(mAdapter);
        mListView.setVisibility(View.GONE);
        refreshViewData();
    }

    @Override
    public void registerRxBus() {
        Disposable quoteAllRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_SYMBOL_ALLLIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        onSymbolNotify();
                    }
                });

        bindSubscription(quoteAllRegister);

        Disposable positionListRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_POSTION_LIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        Logger.i("持仓列表刷新MainActivity 持仓列表回包接收到回调");
                        refreshViewData();
                    }
                });
        bindSubscription(positionListRegister);

        Disposable quoteListRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_SYMBOL_LIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        onSymbolNotify();
                    }
                });

        bindSubscription(quoteListRegister);

        Disposable quoteUpdateRegister = RxBus.getInstance().register(GTSConst.REPLY_SYMBOL_UPDATE + "", DataItemDetail.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataItemDetail>() {

                    @Override
                    public void accept(@NonNull DataItemDetail model) throws Exception {
                        onSymbolNotify();
                    }
                });

        bindSubscription(quoteUpdateRegister);

        Disposable quoteTickRegister = RxBus.getInstance().register(GTSConst.REPLY_SYMBOL_TICK_UPDATE + "", DataItemDetail.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataItemDetail>() {

                    @Override
                    public void accept(@NonNull DataItemDetail model) throws Exception {
                        if (null != model) {
                            onSymbolNotify(model.getInt(GTSConst.JSON_KEY_CODEID));
                        }
                    }
                });

        bindSubscription(quoteTickRegister);
    }

    /**
     * 刷新行情界面数据
     */
    protected void refreshViewData() {
        Logger.e("QuoteSelfFragment refreshViewData " + mZoneType + (null == mAdapter) + (null == mEmptyLayout) + (null == mListView));
        if (null == mAdapter || null == mEmptyLayout || null == mListView) {
            return;
        }
        if (!mListView.mIsOnTouch && !mListView.mIsScrolling) {
            mAdapter.refreshSortData(mSortType);
        }
        Logger.e("QuoteSelfFragment isLoading " + DataManager.instance().getLoadDataState(mZoneType + ""));
        if (mAdapter.getItemCount() < 1) {
            mListView.setVisibility(View.GONE);
            mEmptyLayout.setVisibility(View.VISIBLE);
        } else {
            mListView.setVisibility(View.VISIBLE);
            mEmptyLayout.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.percent_view)
    void onPercentClick() {
        if (CommonUtils.isFastDoubleClick()) {
            return;
        }
        if (null == mAdapter || mAdapter.getItemCount() < 1) {
            return;
        }
        if (mSortType == AppContances.SORT_NORMAL_TYPE) {
            mSortType = AppContances.SORT_DOWN_TYPE;
            mPrecentView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.a_quote_sortdown, 0);
            mPrecentView.setTextColor(getResources().getColor(R.color.color_w));
            MobclickEventUtlis.MobclickEventByAccountType(getActivity(), "ClickChangeSort2");
//            PackStatis.getToService(PackStatis.EventAction.CLICKCHANGESORT.getValue(),PackStatis.EventCategory.MARKET.getValue(),null,"2");
        } else if (mSortType == AppContances.SORT_DOWN_TYPE) {
            mSortType = AppContances.SORT_UP_TYPE;
            mPrecentView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.a_quote_sortup, 0);
            MobclickEventUtlis.MobclickEventByAccountType(getActivity(), "ClickChangeSort2");
            mPrecentView.setTextColor(getResources().getColor(R.color.color_w));
//            PackStatis.getToService(PackStatis.EventAction.CLICKCHANGESORT.getValue(),PackStatis.EventCategory.MARKET.getValue(),null,"1");
        } else if (mSortType == AppContances.SORT_UP_TYPE) {
            mSortType = AppContances.SORT_NORMAL_TYPE;
            mPrecentView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.a_quote_sortstay, 0);
            mPrecentView.setTextColor(getResources().getColor(R.color.color_c));
            MobclickEventUtlis.MobclickEventByAccountType(getActivity(), "ClickChangeSort2");
//            PackStatis.getToService(PackStatis.EventAction.CLICKCHANGESORT.getValue(),PackStatis.EventCategory.MARKET.getValue(),null,"3");
        }
        Logger.e("排序类型点击 == " + mSortType);
        if (null != mAdapter) {
            mAdapter.refreshSortData(mSortType);
        }
//        MobclickEventUtlis.MobclickEventByAccountType(getActivity(),"Range_up");
    }

    @Override
    public void onSendQuote() {
        AppTerminal.instance().sendQuoteSubscribe(DataManager.instance().getQuoteSubscribeCodes(mZoneType));
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshViewData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {//下面的onHiddenChanged，替换为现在的setUserVisibleHint
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            startCountDownTimer();
            onSendQuote();
            refreshViewData();
        }
    }

//    @Override
//    public void onHiddenChanged(boolean hidden) {//在此 fragment直接被作为viewPager的item返回给外层的时候，这个onHiddenChanged方法并不会因为 viewPager的滑动切换而执行
//        super.onHiddenChanged(hidden);
//        if (!hidden) {
//            startCountDownTimer();
//            onSendQuote();
//            refreshViewData();
//        }
//    }

    @Override
    public void onSymbolNotify() {
        super.onSymbolNotify();
//        Logger.i("QuoteItem onSymbolNotify 收到行情列表回调操作 " + mZoneType);
        refreshViewData();
    }

    @Override
    public void onSymbolNotify(int codeId) {
        super.onSymbolNotify(codeId);
        if (null != mListView && !mListView.mIsOnTouch && !mListView.mIsScrolling) {
//            Logger.e("QuoteItem onSymbolNotify 收到行情列表回调操作 codeId = " + codeId);
            if (null != mAdapter) {
                mAdapter.refreshData(codeId);
            }
        }
    }


}